package com.echo.demo;

import com.echo.codec.MapDecoder;
import com.echo.codec.MessageDecoder;
import com.echo.codec.MessageEncoder;
import com.echo.codec.RpcDecoder;
import com.echo.codec.RpcEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {

    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workGroup)
                .channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new RpcDecoder(StudentDto.class));
                        pipeline.addLast(new RpcEncoder(StudentDto.class));
                        pipeline.addLast(new ServerHandler());
                    }
                });
        ChannelFuture f = bootstrap.bind(8000).sync();
        Channel channel = f.channel();
//        ExecutorService executorService = Executors.newFixedThreadPool(100);
//        for (int i = 0; i < 1000; i++) {
//            int finalI = i;
//            executorService.submit(() -> {
//                HashMap<String, String> map = new HashMap<>();
//                map.put("1", "" + finalI);
//                channel.writeAndFlush(map);
//            });
//        }
//        f.channel().closeFuture().sync();
    }
}
